//
//  CacheDataUtil.swift
//  shopDemo
//
//  Created by wulanzhou on 2017/7/17.
//  Copyright © 2017年 wulanzhou. All rights reserved.
//

import UIKit

class CacheDataUtil: NSObject {

    /// 删除缓存值
    ///
    /// - Parameter key: 缓存key
    class func removeKey(key:String?){
    
        if key != nil {
            UserDefaults.standard.removeObject(forKey: key!)
            UserDefaults.standard.synchronize()
        }
        
    }
    
    /// 设置缓存值
    ///
    /// - Parameters:
    ///   - value: 值
    ///   - key: key
    class func setCache(value:AnyObject?,key:String?) {
        
        if (value != nil && key != nil){
            UserDefaults.standard.set(value!, forKey: key!)
            UserDefaults.standard.synchronize()
        }
        
    }
    
    //取得缓存值
    class func valueForKey(key:String) -> Any? {
        if let value = UserDefaults.standard.object(forKey: key) {
            return value
        }
        return nil
        
    }

    //设置缓存值(缓存值序列化)
    class func setArchiver(key:String,object:AnyObject?) {
        if object != nil {
            let source:Data = NSKeyedArchiver.archivedData(withRootObject: object!)
            UserDefaults.standard.set(source, forKey: key)
            UserDefaults.standard.synchronize()
        }
    }
    
    class func unarchiveValue(key:String) -> AnyObject?{
        var obj:AnyObject?
        if let source:Data = UserDefaults.standard.object(forKey: key) as? Data{
            obj = NSKeyedUnarchiver.unarchiveObject(with: source) as AnyObject
        }
        return obj
    }
}
